import { defineStore } from 'pinia';
import { ref } from 'vue';
type Config = { name: string; configName: string; value: any };
// 定义 Store
export const useConfigStore = defineStore(
  'config',
  () => {
    // 配置信息
    const config = ref<Config[]>([]);

    // 保存配置信息
    const pushConfig = (val: Config) => {
      config.value.push(val);
    };
    // 获取配置信息
    const getConfig = () => config.value;
    // 根据名称获取配置信息
    const getConfigByName = (name: string) => {
      let result = [] as Config[];
      config.value.find((item) => {
        if (item.name === name) {
          result.push(item);
        }
      });
      return result;
    };
    // 根据名称和配置名称移除配置信息
    const removeConfigByNameAndConfigName = (
      name: string,
      configName: string,
    ) => {
      config.value = config.value.filter(
        (item) => item.name !== name || item.configName !== configName,
      );
    };
    // 记得 return
    return {
      config,
      pushConfig,
      getConfig,
      getConfigByName,
      removeConfigByNameAndConfigName,
    };
  },
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
    },
  },
);
